#include "Common.hpp"
#include "Log.hpp"

using namespace LogModule;

class Command
{
public:
    Command()
    {
        _whiteListCommand.insert("ls");
        _whiteListCommand.insert("ll");
        _whiteListCommand.insert("whoami");
    }
    
    bool IsSafeCommand(const std::string cmd)
    {
        auto iter = _whiteListCommand.find(cmd);
        return iter != _whiteListCommand.end();
    }

    std::string Excute(const std::string cmd, InetAddr &addr)
    {
        if(!IsSafeCommand(cmd))
        {
            return std::string("坏人");
        }

        std::string who = addr.StringAddr();

        FILE *fp = popen(cmd.c_str(), "r");
        if(fp == nullptr)
        {
            return "你要执行的命令不存在：" + cmd;
        }
        std::string res;
        char line[1024];
        while(fgets(line, sizeof(line), fp))
        {
            res += line;
        }
        pclose(fp);
        std::string result =  who + " Excute done, result is: \n" + res;
        LOG(LogLevel::DEBUG) << result;
        return result;
    }

    ~Command()
    {}
private:
std::unordered_set<std::string> _whiteListCommand;
};